/**
 * 解析导入消息
 * 格式：完成!成功{},失败{}!失败消息:{}
 * @param {string} message 原始消息
 * @returns {object} 解析后的结果
 */
export function parseImportMessage(message) {
  if (!message) {
    return {
      isSuccess: false,
      successCount: 0,
      failedCount: 0,
      failedRecords: [],
      rawMessage: message
    }
  }

  try {
    // 正则表达式匹配：完成!成功{数字},失败{数字}!失败消息:{内容}
    const regex = /完成!成功(\d+),失败(\d+)!失败消息:(.+)/
    const match = message.match(regex)

    if (match) {
      const successCount = parseInt(match[1]) || 0
      const failedCount = parseInt(match[2]) || 0
      const failedMessage = match[3] || ''

      // 解析失败消息
      let failedRecords = []
      if (failedMessage && failedMessage.trim() !== '') {
        // 处理HTML格式的失败消息
        if (failedMessage.includes('<br/>')) {
          // 按<br/>分割，提取每行的错误信息
          const lines = failedMessage.split('<br/>').filter(line => line.trim())
          failedRecords = lines.map((line, index) => {
            // 匹配格式：第X行导入失败：错误信息
            const lineMatch = line.match(/第(\d+)行导入失败：(.+)/)
            if (lineMatch) {
              return {
                row: parseInt(lineMatch[1]),
                error: lineMatch[2].trim(),
                field: '',
                value: ''
              }
            } else {
              // 如果格式不匹配，直接使用原文
              return {
                row: index + 1,
                error: line.trim(),
                field: '',
                value: ''
              }
            }
          })
        } else {
          // 尝试解析JSON格式
          try {
            const jsonData = JSON.parse('{' + failedMessage + '}')
            if (Array.isArray(jsonData)) {
              failedRecords = jsonData
            } else if (typeof jsonData === 'object') {
              // 将对象转换为数组格式
              failedRecords = Object.keys(jsonData).map(key => ({
                row: key,
                error: jsonData[key],
                field: '',
                value: ''
              }))
            }
          } catch (e) {
            // 如果不是JSON，按行分割处理
            const lines = failedMessage.split(',').filter(line => line.trim())
            failedRecords = lines.map((line, index) => ({
              row: index + 1,
              error: line.trim(),
              field: '',
              value: ''
            }))
          }
        }
      }

      return {
        isSuccess: failedCount === 0,
        successCount,
        failedCount,
        failedRecords,
        rawMessage: message,
        totalCount: successCount + failedCount
      }
    }

    // 如果格式不匹配，尝试其他可能的格式
    return parseAlternativeFormats(message)

  } catch (error) {
    console.error('解析导入消息失败:', error)
    return {
      isSuccess: false,
      successCount: 0,
      failedCount: 0,
      failedRecords: [{
        row: 1,
        error: message,
        field: '',
        value: ''
      }],
      rawMessage: message
    }
  }
}

/**
 * 解析其他可能的消息格式
 */
function parseAlternativeFormats(message) {
  // 格式1: 导入成功5条，失败3条
  const format1 = /导入成功(\d+)条[，,]失败(\d+)条/
  const match1 = message.match(format1)
  if (match1) {
    return {
      isSuccess: parseInt(match1[2]) === 0,
      successCount: parseInt(match1[1]) || 0,
      failedCount: parseInt(match1[2]) || 0,
      failedRecords: [],
      rawMessage: message
    }
  }

  // 格式2: 成功X条，失败Y条
  const format2 = /成功(\d+)条[，,]失败(\d+)条/
  const match2 = message.match(format2)
  if (match2) {
    return {
      isSuccess: parseInt(match2[2]) === 0,
      successCount: parseInt(match2[1]) || 0,
      failedCount: parseInt(match2[2]) || 0,
      failedRecords: [],
      rawMessage: message
    }
  }

  // 默认处理：将整个消息作为错误信息
  return {
    isSuccess: false,
    successCount: 0,
    failedCount: 1,
    failedRecords: [{
      row: 1,
      error: message,
      field: '',
      value: ''
    }],
    rawMessage: message
  }
}

/**
 * 格式化导入结果用于显示
 */
export function formatImportResult(result) {
  if (!result) return ''

  const { successCount, failedCount, totalCount } = result

  if (failedCount === 0) {
    return `导入完成！成功导入 ${successCount} 条数据`
  } else {
    return `导入完成！成功 ${successCount} 条，失败 ${failedCount} 条，共 ${totalCount} 条`
  }
}

/**
 * 生成表格列配置
 */
export function getFailedRecordsTableColumns() {
  return [
    {
      prop: 'row',
      label: '行号',
      width: 80,
      align: 'center'
    },
    {
      prop: 'field',
      label: '字段',
      width: 120,
      align: 'center'
    },
    {
      prop: 'value',
      label: '值',
      width: 150,
      align: 'center'
    },
    {
      prop: 'error',
      label: '错误信息',
      align: 'left',
      showOverflowTooltip: true
    }
  ]
}
